package com.whmnx.main.ui.view;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.whmnx.base.bean.ProductBean;
import com.whmnx.base.bean.SpecBean;
import com.whmnx.base.utils.ImageUtil;
import com.whmnx.base.utils.UItils;
import com.whmnx.base.view.MyGridView;
import com.whmnx.base.view.RoundImageView;
import com.whmnx.main.R;
import com.whmnx.main.ui.adapter.GirdDropDownAdpter;
import com.whmnx.main.ui.adapter.SpceAdapter;

import java.lang.reflect.Method;
import java.util.ArrayList;

import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * Company 武汉麦诺软创
 *
 * @author lizhe
 * @date 2018/11/2
 */

public class SelectParamPopupWindow extends PopupWindow {

    private View mRealContentLayout;

    private ArrayList<SpecBean.ItemsBean.SpecItemsBean> list;

    private TextView textSpec;
    private TextView textPrice;

    private String goodsId;
    private String priceId;
    private int count = 1;
    private int limitCount;
    private String productSPEC_name,productSPEC_Price;
    private boolean flag;


    public SelectParamPopupWindow(final Activity activity, String stroName, ProductBean productBean, int type) {
        super(activity.getLayoutInflater().inflate(R.layout.popup_select_param2, null), UItils.getScreenWidth(), UItils.getScreenHeight());
        getContentView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });


        list = new ArrayList();

        mRealContentLayout = getContentView().findViewById(R.id.realContentLayout);
        mRealContentLayout.setVisibility(View.INVISIBLE);
        LinearLayout relativeLayout = mRealContentLayout.findViewById(R.id.rl_count);
        TextView tvCountTitle = mRealContentLayout.findViewById(R.id.tv_count_title);

        RecyclerView recyclerView = mRealContentLayout.findViewById(R.id.rv_list1);
        MyGridView gv = mRealContentLayout.findViewById(R.id.gv);
        TextView tvStock = mRealContentLayout.findViewById(R.id.tv_stock);

        RoundImageView ivImg = mRealContentLayout.findViewById(R.id.iv_image);
        TextView tvName = mRealContentLayout.findViewById(R.id.tv_Name);
        TextView tvPrice = mRealContentLayout.findViewById(R.id.tv_price);


        GirdDropDownAdpter cityAdapter = new GirdDropDownAdpter(activity, productBean.SPECModel);
        gv.setAdapter(cityAdapter);
        //cityAdapter.setCheck(0);


        if (!TextUtils.isEmpty(productBean.Product_Image)){
            String[] split = productBean.Product_Image.split(",");
            String url = split[0];
            ImageUtil.setImage(ivImg,url);
        }
        tvName.setText(productBean.Product_Name);
        tvPrice.setText("￥" + productBean.Product_Price);

        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(activity,4);
        recyclerView.setLayoutManager(gridLayoutManager1);
        SpceAdapter spceAdapter = new SpceAdapter(activity);
        recyclerView.setAdapter(spceAdapter);

        spceAdapter.replaceAll(productBean.SPECModel,true);

        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                flag = true;
                Button tv =  view.findViewById(R.id.tv);
                if (tv.isSelected() == false){
                    productSPEC_name = productBean.SPECModel.get(position).ProductSPEC_Name;
                    productSPEC_Price = productBean.SPECModel.get(position).ProductSPEC_Price;
                    tv.setSelected(true);
                    tvPrice.setText("￥" + (productBean.SPECModel.get(position).ProductSPEC_Price));
                }else {
                    tv.setSelected(false);
                }
            }
        });


//       textPrice.setText(StringUtil.wanString(specBean.getGoodsInfo().getGoods_Price()));
       // tvStock.setText("库存"+specBean.getGoodsInfo().getStock()+"件");


       /* if (type == 0){
            tvCountTitle.setVisibility(View.INVISIBLE);
            relativeLayout.setVisibility(View.GONE);
        }else {
            tvCountTitle.setVisibility(View.VISIBLE);
            relativeLayout.setVisibility(View.VISIBLE);
        }*/

        final TextView tvCount = mRealContentLayout.findViewById(R.id.tv_count);

       // tvCount.setText(String.valueOf(specBean.getGoodsInfo().getGoods_LimitCount()));
     //   count = limitCount;
        // -
        mRealContentLayout.findViewById(R.id.tv_jian).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (count > limitCount){
                    count -= limitCount;
                    tvCount.setText(String.valueOf(count));
                }
            }
        });

        //+
        mRealContentLayout.findViewById(R.id.tv_jia).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count += limitCount;
                tvCount.setText(String.valueOf(count));
            }
        });

        mRealContentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        mRealContentLayout.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

//        mRealContentLayout.findViewById(R.id.tv_add_car).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (mListener != null){
//                    if (TextUtils.isEmpty(goodsId)){
//                        return;
//                    }
//                    if (TextUtils.isEmpty(priceId)){
//                        ToastUtils.showShort("请选择商品规格");
//                        return;
//                    }
//                    dismiss();
//                    mListener.onAddCar(goodsId,priceId,count);
//                }
//            }
//        });

        mRealContentLayout.findViewById(R.id.tv_buy).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null){
                    if (!flag){
                        ToastUtils.showShort("请选择商品规格");
                        return;
                    }
                    if (count <= 0){
                        ToastUtils.showShort("数量不能为零");
                        return;
                    }
                    dismiss();
                    mListener.onAddCar(productSPEC_name,productSPEC_Price,count);
                }
            }
        });
        //加入购入车
        mRealContentLayout.findViewById(R.id.tv_add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null){
                    if (!flag){
                        ToastUtils.showShort("请选择商品规格");
                        return;
                    }
                    if (count <= 0){
                        ToastUtils.showShort("数量不能为零");
                        return;
                    }
                    dismiss();
                    mListener.onBuy(productSPEC_name,productSPEC_Price,count);
                }
            }
        });

        setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        setOutsideTouchable(true);
        setTouchable(true);
        setFocusable(true);
        //sdk > 21 解决 标题栏没有办法遮罩的问题
        setClippingEnabled(false);
    }

    public void showPop(View parent,Activity activity) {
        if (isShowing() || getContentView() == null) {
            return;
        }

        showAtLocation(parent, Gravity.BOTTOM, 0, getNavigationBarHeight(activity));

        mRealContentLayout.setVisibility(View.VISIBLE);
        Animation inAnimation = AnimationUtils.loadAnimation(getContentView().getContext(), R.anim.dialog_in_button);
        mRealContentLayout.startAnimation(inAnimation);
    }

    /**
     * 按返回键的时候会调用这个方法
     * 所以这里重写该方法，主要是解决按返回键也具有动画效果
     */
    @Override
    public void dismiss() {
        if (!isShowing()) {
            return;
        }

        mRealContentLayout.setVisibility(View.VISIBLE);
        Animation outAnimation = AnimationUtils.loadAnimation(getContentView().getContext(), R.anim.dialog_out_button);
        outAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                SelectParamPopupWindow.super.dismiss();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mRealContentLayout.startAnimation(outAnimation);
        if (mListener != null) {
            mListener.onCancel();
        }
    }

    private OnCancelListener mListener;

    public void setOnCancelListener(OnCancelListener listener) {
        mListener = listener;
    }

    public interface OnCancelListener {
        void onCancel();

        void onBuy(String goodsId, String priceId, int count);

        void onAddCar(String goodsId, String priceId, int count);

    }




    /**
     * 设置页面的透明度
     *
     * @param bgAlpha 1表示不透明
     */
    public static void setBackgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        if (bgAlpha == 1) {
            //不移除该Flag的话,在有视频的页面上的视频会出现黑屏的bug
            activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        } else {
            //此行代码主要是解决在华为手机上半透明效果无效的bug
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        }

        activity.getWindow().setAttributes(lp);
    }


    public static int getNavigationBarHeight(Activity activity) {
        if (hasSoftKeys(activity.getWindowManager())) {
            Resources resources = activity.getResources();
            int resourceId = resources.getIdentifier("navigation_bar_height",
                    "dimen", "android");
            //获取NavigationBar的高度
            int height = resources.getDimensionPixelSize(resourceId);
            return height;
        }
        return 0;
    }

    /**
     * 判断底部navigator是否已经显示
     * @param windowManager
     * @return
     */
    private static boolean hasSoftKeys(WindowManager windowManager){
        Display d = windowManager.getDefaultDisplay();


        DisplayMetrics realDisplayMetrics = new DisplayMetrics();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            d.getRealMetrics(realDisplayMetrics);
        }


        int realHeight = realDisplayMetrics.heightPixels;
        int realWidth = realDisplayMetrics.widthPixels;


        DisplayMetrics displayMetrics = new DisplayMetrics();
        d.getMetrics(displayMetrics);


        int displayHeight = displayMetrics.heightPixels;
        int displayWidth = displayMetrics.widthPixels;


        return (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0;
    }

    /**
     * 获取底部虚拟键盘的高度
     */
    public int getBottomKeyboardHeight(Activity context){
        int screenHeight =  getAccurateScreenDpi(context)[1];
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int heightDifference = screenHeight - dm.heightPixels;
        return heightDifference;
    }


    /**
     * 获取精确的屏幕大小
     */
    public int[] getAccurateScreenDpi(Activity context) {
        int[] screenWH = new int[2];
        Display display = context.getWindowManager().getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        try {
            Class<?> c = Class.forName("android.view.Display");
            Method method = c.getMethod("getRealMetrics",DisplayMetrics.class);
            method.invoke(display, dm);
            screenWH[0] = dm.widthPixels;
            screenWH[1] = dm.heightPixels;
        }catch(Exception e){
            e.printStackTrace();
        }
        return screenWH;
    }
}